<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="state.title"
    width="760px"
    cancelText="关闭"
    okText="保存"
    @ok="onSave"
    :maskClosable="false"
  >
    <div class="card">
      <div class="c-title"> 基础信息</div>
      <BasicForm @register="registerForm1" class="form" >
        <template #birthday="{ model,field }">
          <a-date-picker v-model:value="model[field]" @change="onChangeDate" hange="" :disabled-date="disabledDate"></a-date-picker>
        </template>

        <template #yinli="{ model,field }">
          <div style="padding-top: 5px" v-if="state.yinDate">{{state.yinDate}}</div>
        </template>
      </BasicForm>
    </div>
    <div class="card">
      <div class="c-title"> 补充信息</div>
      <BasicForm @register="registerForm2" class="form" />
    </div>
  </BasicDrawer>
</template>
<script setup>
  import { defineOptions, reactive, ref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { GET, POST, PUT } from '@/api/http';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { solar2Lunar } from '@/api/util.js';
  import dayjs from 'dayjs';
  import {
    marrys,
    memberSources,
    pastBeautyHistorys,
    skincareHabits,
    skincareNeeds,
    skinConditions,
    allergys,
  } from '@/api/ds.js';
  defineOptions({ name: 'MemberEdit' });
  const emit = defineEmits(['complete']);
  const state = reactive({ title: '', behavior: '',yinDate: '' });
  const onChangeDate = (e) => {
    const changeDate = dayjs(e).format('YYYY-MM-DD')
    state.yinDate = e?solar2Lunar(changeDate):''
  }
  const disabledDate = current => {
    return current && current > dayjs().endOf('day');
  };
  const { createMessage } = useMessage();
  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },
    schemas: [
      {
        label: '顾客姓名',
        field: 'realName',
        required: true,
        component: 'Input',
        colProps: {
          span: 14,
        },
      },
      {
        label: '手机号码',
        field: 'mobile',
        component: 'Input',
        rules: [
          { required: true },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
          {
            validator: (_, value) =>
              !!value && recordRef.value?.mobile !== value
                ? POST(
                    '/membership/checkMemberIsRegister',
                    { mobile: value },
                    { errorMessageMode: 'none' },
                  )
                : Promise.resolve(),
          },
        ],
        colProps: {
          offset: 1,
          pull: 1,
          span: 14,
        },
      },

      {
        label: '进店渠道',
        field: 'memberSource',
        required: true,
        component: 'Select',
        dynamicDisabled: () => state.behavior !== 'add',
        componentProps: {
          options: memberSources,
        },
        colProps: {
          offset: 1,
          pull: 1,
          span: 14,
        },
      },
      {
        label: '婚姻状况',
        field: 'marry',
        required: false,
        component: 'RadioGroup',
        componentProps: {
          options: marrys,
        },
      },
      {
        label: '阳历生日',
        field: 'birthday',
        required: false,
        component: 'DatePicker',
        colProps: {
          offset: 1,
          pull: 1,
          span: 14,
        },
        slot: 'birthday',
      },
      {
        label: '阴历生日',
        field: 'yinli',
        required: false,
        ifShow: ({ values }) => {
          return !!values.birthday;
        },
        component: 'DatePicker',
        colProps: {
          offset: 1,
          pull: 1,
          span: 14,
        },
        slot: 'yinli',
      },

      {
        label: '职业',
        field: 'job',
        required: false,
        component: 'Input',
        colProps: {
          offset: 1,
          pull: 1,
          span: 14,
        },
      },

      {
        label: '家庭地址',
        field: 'homeAddress',
        required: false,
        component: 'InputTextArea',
      },
    ],
    showActionButtonGroup: false,
  });

  const [registerForm2, form2] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '皮肤情况',
        field: 'allergys',
        required: false,
        component: 'CheckboxGroup',
        componentProps: {
          options: allergys,
          onChange(values) {
            console.log(values)
            console.log(values.findIndex((s) => console.log(s, '1111111')))
            if (Array.isArray(values)) {
              if (values.findIndex((s) => s === '无过敏史') > -1 && values.length > 1) {
                values = ['无过敏史'];
                form2.setFieldsValue({ allergys: values });
              }
            }
          },
        },
      },
      {
        label: '护肤习惯',
        field: 'skincareHabits',
        required: false,
        component: 'CheckboxGroup',
        componentProps: {
          options: skincareHabits,
        },
      },

      {
        label: '护肤诉求',
        field: 'skincareNeeds',
        required: false,
        component: 'CheckboxGroup',
        componentProps: {
          options: skincareNeeds,
        },
      },

      {
        label: '过往美容史',
        field: 'pastBeautyHistory',
        required: false,
        component: 'CheckboxGroup',
        componentProps: {
          options: pastBeautyHistorys,
          onChange(values) {
            if (Array.isArray(values)) {
              if (values.findIndex((s) => s === '无') > -1 && values.length > 1) {
                values = ['无'];
                form2.setFieldsValue({ pastBeautyHistory: values });
              }
            }
          },
        },
      },

      {
        label: '补充说明',
        field: 'additionalRemarks',
        required: false,
        component: 'InputTextArea',
      },
    ],
    showActionButtonGroup: false,
  });

  const formList = [form1, form2];
  const recordRef = ref({});

  const [registerDrawer, { closeDrawer }] = useDrawerInner(async ({ behavior, memberCode }) => {
    state.title = behavior === 'add' ? '新增客户' : '编辑客户';
    state.behavior = behavior;
    state.yinDate = ''
    const initData = {};
    recordRef.value = {};

    if (behavior !== 'add') {
      const result = (await GET('/membership/getMemberBaseInfo', { memberCode })) ?? {};
      const { allergy, skincareHabits, skincareNeeds, pastBeautyHistory } = result;

      result.allergys = allergy?.split(',') ?? [];
      result.skincareHabits = skincareHabits?.split(',') ?? [];
      result.skincareNeeds = skincareNeeds?.split(',') ?? [];
      result.pastBeautyHistory = pastBeautyHistory?.split(',') ?? [];
      state.yinDate = result.birthday?solar2Lunar(result.birthday):''
      recordRef.value = result;
    }
    //初始化表单
    Object.assign(initData, recordRef.value);
    formList.forEach((f) => {
      f.setFieldsValue(initData);
    });
  });

  async function onSave() {
    await Promise.all(formList.map((f) => f.validate()));
    const formData = formList.reduce((prev, f) => Object.assign(prev, f.getFieldsValue()), {});
    
    //保存
    const data = { ...recordRef.value, ...formData };
    data.nickName ||= data.realName;

    await (state.behavior === 'add'
      ? POST('/membership/addMemberBaseInfo', data)
      : PUT('/membership/updateMemberBaseInfoBean', data));

    createMessage.success('客户信息已保存');
    emit('complete');
    closeDrawer();
  }
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 12px;
    padding: 0 16px;
    background-color: #fff;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      column-gap: 8px;
      color: #091f3d;
      font-size: 14px;
      font-weight: 600;
    }

    .form {
      padding: 24px 12px 0 0;
    }
  }
</style>
